﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using log4net;
using OpelWelcomeScreenWeb.NetUtils.Settings;
using Newtonsoft.Json;
using OpelWelcomeScreenWeb.NetUtils;
using System.Text;
using nsBaseClass;
using OpelWelcomeScreenWeb.NetUtils;
using OpelWelcomeScreenWeb.Models;

namespace OpelWelcomeScreenWeb
{
    public partial class Services1 : System.Web.UI.Page
    {
        protected static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        protected static readonly StringBuilder sb = new StringBuilder();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var Settings = AppConfig.GetWebAppSettings();
                var dayNames = AppConfig.GetOpelWelcomeSettings("dayNames");
                var dateformat = Settings[Constants.DATETIME_FORMAT];
                var path = Page.Server.MapPath("Assets/images");
                logger.Debug(path);

                var site = StringUtils.DefaultIfBlank(Request.QueryString["site"], Settings[Constants.DEFAULT_SITE]);
                var overdue = StringUtils.DefaultIfBlank(Request.QueryString["overdue"], Settings[Constants.DEFAULT_OVERDUE]);
                var aftertime = StringUtils.DefaultIfBlank(Request.QueryString["aftertime"], Settings[Constants.DEFAULT_AFTERTIME]);
                var sessionId = StringUtils.DefaultIfBlank(Request.QueryString["sessionID"], Settings[Constants.DEFAULT_SESSION_ID]);
                var temp = Page.Request.QueryString["counter"];
                var counter = 0;
                Int32.TryParse(temp, out counter);
                //connect to DB
                var dbConfig = this.connectDb(sessionId);
                if (dbConfig != null)
                {
                    site = StringUtils.DefaultIfBlank(dbConfig.Site, "");
                }
                sb.Length = 0;
                sb
                    .Append("Site=").Append(site)
                    .Append(",OverDue=").Append(overdue)
                    .Append(",AfterTime=").Append(aftertime)
                    .Append(",Counter=").Append(counter)
                    .Append(",SessionID=").Append(sessionId);
                logger.Debug(sb);

                var ht = new Hashtable();
                var noimage = false;
                if (counter > 0 && counter % 2 == 1)
                {
                    var ads = Services.loadAds(path);
                    var count = ads.Count;
                    noimage = count == 0;
                    ht["dt"] = StringUtils.UppercaseFirst(dayNames[(int)DateTime.Now.DayOfWeek]) + ", " + DateTime.Now.ToString(dateformat);
                    ht["delay"] = Int32.Parse(Settings[Constants.DEFAULT_DELAY_IMAGE]);
                    if (!noimage)
                    {
                        ht["image"] = ads[((counter / 2) + count) % count];
                    }
                }
                if (counter % 2 == 0 || counter > 0 && noimage)
                {
                    var workOrders = Services.loadWorkOrders(site, overdue, aftertime);
                    ht["dt"] = StringUtils.UppercaseFirst(dayNames[(int)DateTime.Now.DayOfWeek]) + ", " + DateTime.Now.ToString(dateformat);
                    ht["delay"] = Int32.Parse(Settings[Constants.DEFAULT_DELAY_IMAGE]);
                    ht["tbldata"] = workOrders;
                    ht["dispStatusColor"] = "true".Equals(Settings[Constants.DISPLAY_STATUS_COLOR]);
                    ht["colFullscreen"] = Int32.Parse(Settings[Constants.COLUMNS_FULLSCREEN]);
                    ht["scrollerDelay"] = Int32.Parse(Settings[Constants.SCROLLER_DELAY]);
                    ht["scrollerDuration"] = Int32.Parse(Settings[Constants.SCROLLER_DURATION]);
                }

                var json = JsonConvert.SerializeObject(ht);
                Page.Response.ContentType = "application/json";
                Page.Response.Write(json);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                Page.Response.Write("Error: Please check log for details");
            }
            Page.Response.End();
        }

        public DBConfig connectDb(string sessionID)
        {

            var objGlobal = new clsGlobalVariable();
            if (String.IsNullOrEmpty(sessionID))
            {
                var Settings = AppConfig.GetWebAppSettings();
                objGlobal.InitFromCommandLine(
                    Settings["DMSDBName"],
                    Settings["WinAut"],
                    Settings["DMSUserName"],
                    Settings["DMSDBPass"],
                    Settings["Site"]
                );
            }
            else
            {
                DbConfigSection config = new DbConfigSection();
                config = ConfigurationManager.GetSection("dbConfigs") as DbConfigSection;
                foreach (DBConfig cf in config.dbConfigs)
                {
                    //logger.Debug(cf.sessionID);
                    //logger.Debug(cf.Site); 
                    if (cf.sessionID.Equals(sessionID))
                    {
                        objGlobal.InitFromCommandLine(cf.DMSDBName, cf.WinAut, cf.DMSUserName, cf.DMSDBPass, cf.Site);
                        return cf;
                    }
                }
            }
            return null;
        }
    }
}
